﻿Imports System.Threading
Imports System.IO
Imports System.Net.Sockets

Public Class Service1

    Private m_LocalIP As String = System.Net.Dns.GetHostName()
    'points to machine service is running on

    Private m_Watcher_IP As String
    'Listening Log Watcher Host IP

    Private m_Watcher_Port As String
    'Listening Log Watcher Host Port

    Private m_ErrorLogFile As String
    'Log file where we can log useful information while service is running

    Protected Overrides Sub OnStart(ByVal args() As String)
        ' Add code here to start your service. This method should set things
        ' in motion so your service can do its work.

        ' Add code here to start your service. This method should set things

        ' in motion so your service can do its work.


        'open config file:    LogMonitoringService.exe.config

        m_Watcher_IP = System.Configuration.ConfigurationSettings.AppSettings.Get("watcher_ip")
        m_Watcher_Port = System.Configuration.ConfigurationSettings.AppSettings.Get("watcher_port")
        m_ErrorLogFile = Path.Combine(GetApplicationDirectory(), "log_monitoring_service_errors.txt")

        WorkerThread = New Thread(AddressOf WatchEventLog)
        WorkerThread.Start()

    End Sub

    Protected Overrides Sub OnStop()
        ' Add code here to perform any tear-down necessary to stop your service.
    End Sub

    Public Sub WatchEventLog()
        Try
            m_LogWatcherLog = New EventLog()
            'just to make sure we have LogMonitoringService source registered

            Try
                m_LogWatcherLog.CreateEventSource("LogMonitoringService", "Application")
            Catch
            End Try

            m_LogWatcherLog.Close()
            m_LogWatcherLog = New EventLog("Application", ".", "LogMonitoringService")
            m_LogWatcherLog.Source = "LogMonitoringService"

            'make a record in Application log:    

            m_LogWatcherLog.WriteEntry("LogWacther started." & vbCrLf & _
                        "Send data to [" & m_Watcher_IP & ":" & m_Watcher_Port & "]" & vbCrLf & _
                        "Error file [" & m_ErrorLogFile & "]", _
                        EventLogEntryType.Information)

            'make a record in log file:    

            LogError("LogWacther started." & vbCrLf & _
                        "Send data to [" & m_Watcher_IP & ":" & m_Watcher_Port & "]" & vbCrLf & _
                        "Error file [" & m_ErrorLogFile & "]")

            ' "attach" to Application Log

            m_ApplicationLog = New EventLog()
            m_ApplicationLog.Log = "Application"
            AddHandler m_ApplicationLog.EntryWritten, AddressOf ApplicationLog_OnEntryWritten
            m_ApplicationLog.EnableRaisingEvents = True

            ' "attach" to System Log

            m_SystemLog = New EventLog()
            m_SystemLog.Log = "System"
            AddHandler m_SystemLog.EntryWritten, AddressOf SystemLog_OnEntryWritten
            m_SystemLog.EnableRaisingEvents = True

            m_run = True
            Do While (m_run)
                Thread.Sleep(10000)
            Loop

        Catch e As Exception
            Dim Log As New EventLog("Application")
            Log.WriteEntry("Failed to WatchEventLog:" & e.ToString, EventLogEntryType.Error)
            Log.Close()
            Log.Dispose()
        End Try
    End Sub

    Public Sub ApplicationLog_OnEntryWritten(ByVal [source] As Object, _
                          ByVal e As EntryWrittenEventArgs)
        Try
            LogError("Application Log Entry:" & vbCrLf & "Message [" & e.Entry.Message & "]")

            SendEventLogEntryToHost("Application", e.Entry)

        Catch err As Exception
            LogError("Failed to ApplicationLog_OnEntryWritten:" & err.ToString())
        End Try
    End Sub

    Public Sub SystemLog_OnEntryWritten(ByVal [source] As Object, _
               ByVal e As EntryWrittenEventArgs)
        Try
            LogError("System Log Entry:" & vbCrLf & "Message [" & e.Entry.Message & "]")

            'send data to watcher

            SendEventLogEntryToHost("System", e.Entry)

        Catch err As Exception
            LogError("Failed to SystemLog_OnEntryWritten:" & err.ToString())
        End Try
    End Sub

    Private Function SendEventLogEntryToHost(ByVal LogName As String, _
                 ByVal e As EventLogEntry) As Boolean
        Try
            Dim objTCP As Socket
            Dim remoteEndPoint As New IPEndPoint( _
                   IPAddress.Parse(m_Watcher_IP), m_Watcher_Port)

            objTCP = New Socket( _
                    remoteEndPoint.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp)
            objTCP.Connect(remoteEndPoint)

            If objTCP.Connected Then
                LogError("objTCP socket connected to [" & _
                         remoteEndPoint.Address.ToString() & "]" & vbCrLf & _
                         " From Port [" & CType(objTCP.LocalEndPoint,  _
                         IPEndPoint).Port.ToString() & "]")

                'send data to watcher host:

                Dim Message As String = e.TimeGenerated.ToString("MM/dd/yyyy HH:mm:ss") & _
                                       "|" & LogName & "|" & _
                                       e.EntryType.ToString() & "|" & _
                                       e.Message

                Dim sendBytes As Byte() = System.Text.Encoding.ASCII.GetBytes(Message)
                objTCP.Send(sendBytes, sendBytes.Length, SocketFlags.None)

                LogError("objTCP socket sent [" & sendBytes.Length & "] bytes")
            Else
                LogError("objTCP socket did not connected to [" & _
                         remoteEndPoint.Address.ToString() & "]")
            End If

            objTCP.Shutdown(SocketShutdown.Both)
            objTCP.Close()
            LogError("TCP client closed")

        Catch err As Exception
            LogError("Failed to SendEventLogEntryToHost:" & err.ToString())
        End Try
    End Function

End Class
